# encoding: utf-8
class DatainportController < ApplicationController

  def inport_student_info
    a="aaa"
    $allow_validation=false
    schools = {"东财"=>"东北财经大学", "大工"=>"大连理工大学", "海事"=>"大连海事大学"}
    group = {"aaa"=>"金融经济", "bbb"=>"财务会计", "ccc"=>"工程管理", "ddd"=>"信息技术", "eee"=>"法律"}
    group.each do |k, v|
      Spreadsheet.client_encoding = 'UTF-8'
      book = Spreadsheet.open 'C:/'<< k.to_s<<'.xls'
      sheet1 = book.worksheet 0
      sheet1.each do |row|
        s=Student.new
        aa= row[0].to_i.to_s
        aa[1]=""
        s.fid=aa
        s.studentId=row[1].to_s.strip
        s.grade=row[2].to_s.strip
        s.major=row[3].to_s.strip
        s.name=row[4].to_s.strip
        s.university=schools[row[5].strip]
        s.sgroup=v.to_s
        s.save if s.fid!="0"
        a<<s.studentId<<"saved \n"
      end
    end
    $allow_validation=true
    render :layout => false, :text => a
  end

  def inport_attendance_data
    render
  end

  #url"/inport"
  def do_inport
    uploaded_io = request.body
    #filename = "#{Rails.root}/uploads/temp/#{params[:qqfile]}"
    #File.open(filename, 'wb') do |file|
    #  file.write(uploaded_io.read)
    #end
    if inport_to_db(uploaded_io, params[:tid])
      render :text=>"{success: true}"
    else
      render :text=>"{success: false}"
    end
  end


  def inport_to_db(uploaded_io, tid)
    result = true
    begin
      attendances = {}
      Attendance.find_all_by_tclass_id(tid.to_i).each do |a|
        attendances.store a.student.fid, a
      end
      classtime = Tclass.find(tid.to_i).ctime
      Spreadsheet.client_encoding = 'UTF-8'
      book = Spreadsheet.open uploaded_io
      Attendance.transaction do
        sheet = book.worksheet 0
        sheet.each do |row|
          if (attendances.has_key?(row[1].to_s.strip))
            datestr = row[3].to_s.strip<<" "<<row[4].to_s.strip<<":00 +0800"
            time = DateTime.parse(datestr)
            a=attendances[row[1].to_s.strip]
            a.state = 1 if time<=classtime
            a.description = "迟到" if time>classtime
            a.save
          end
        end
      end
    rescue =>e
      logger.error "导入excel出错:"<<e.to_s
      result = false
    ensure
      result
    end
  end

end
